package com.lagou.edu.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.lagou.edu.controller.LoginController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!checkLogin(request)){
            response.sendRedirect("login.jsp");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("333333");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("333333");

    }

    //读取cookie数组，之后迭代出各个cookie
    public boolean checkLogin(HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();//根据请求数据，找到cookie数组

        if (null == cookies || cookies.length == 0) {//如果没有cookie数组
            return false;
        }
        for (Cookie cookie : cookies) {
            if (StringUtils.equals(cookie.getName(), LoginController.USER_NAME) && StringUtils.equals(cookie.getValue(), LoginController.USER_PASSWORD)) {
                return true;
            }
        }
        return false;
    }
}
